#!/bin/bash

rpms_path="/opt/cve"
remote_branch="openEuler-20.03-LTS-SP1"
current_path=$(
    cd "$(dirname $0)"
    pwd
)

function check() {
    if [[ ! -d ${rpms_path} ]]; then
        echo "[ERROR] ${rpms_path} is not exist"
        exit 1
    fi

    if [[ -z ${remote_branch} ]]; then
        echo "[ERROR] The remote branch is not specified"
        exit 1
    fi
}

function run() {
    check

    result_file=${rpms_path}/result.log
    if [[ -f ${result_file} ]]; then
        echo "" >${result_file}
    fi

    rpm_cve_path=$(ls ${rpms_path})
    IFS=$'\n'
    for rpm_cve in ${rpm_cve_path[@]}; do
        if [[ -d ${rpms_path}/${rpm_cve} ]]; then
            rpm_name=$(echo ${rpm_cve} | awk -F '-CVE' '{print $1}')
            patchs=$(find ${rpms_path}/${rpm_cve} -name "*.patch" | sort)
            if [[ -z ${patchs} ]]; then
                echo "[WARRING] ${rpm_name} not found patch" | tee -a ${result_file}
                echo "============================================================="
            else
                /bin/bash ${current_path}/add_patch.sh ${rpm_name} ${remote_branch} "${patchs}"
                add_patch_result=$?
                if [[ ${add_patch_result} -eq 0 ]]; then
                    echo "[INFO] ${rpm_name} apply patch ${patchs} successfully" | tee -a ${result_file}
                    echo "============================================================="
                else
                    echo "[ERROR] ${rpm_name} failed to apply patch ${patchs}" | tee -a ${result_file}
                    echo "============================================================="
                fi
            fi
        fi
    done
}

run